<script>
import { send_days_options, bag_type_options } from "./config";

const INITAIL_DATA = {
  type: {
    id: "",
    name: "",
    group_name: "类型",
  },
  style: {
    id: "",
    name: "",
    group_name: "款型",
  },
  spec: {
    id: "",
    name: "",
    group_name: "规格",
  },
  bom_nums: "",
  capacity: "",
  cbj: "",
  img: "",
  marque: "",
  send_days: "",
  sj: "",
  yj: "",
  materialId: "",
  status: "0",
};

export default {
  props: {
    kindList: {
      type: Array,
      default: [],
    },
    skuMaterialList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      transList: [],
      originalTranList: [], //原始数据备份
      send_days_options,
      bag_type_options,
      skuMaterialIds: [],
      treeList: [],
      oldInputValue: "", // 保存原始数据
      curFocusMaterialId: "", // 保存旧的材质id
      oldMaterialIds: [], // 保存旧的材质ids
    };
  },
  watch: {
    kindList: {
      handler(val) {
        if (val.length) {
          this.transformToTreeList();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    skuMaterialListMap() {
      const optionsMap = this.skuMaterialList.reduce((map, option) => {
        map[option.id] = option.materialName;
        return map;
      }, {});
      return optionsMap;
    },
  },
  methods: {
    transformToTreeList() {
      const initialData = this.kindList.length
        ? _.cloneDeep(this.kindList)
        : [_.cloneDeep(INITAIL_DATA)];
      const { data, materialIdList } = this.transformData(initialData);
      this.treeList = data;
      this.skuMaterialIds = materialIdList;
    },
    transformData(kindList) {
      // 先合并原数组
      const mergeOriginData = this.mergeSameTypeStyleSpec(kindList);
      // 先按 type.id 分组
      const grouped = _.groupBy(mergeOriginData, (item) => item.type.id);

      // 组装树结构
      const data = _.map(grouped, (items) => {
        const { type } = items[0];
        return {
          id: type.id,
          name: type.name,
          group_name: type.group_name,
          children: items.map((item) => ({
            ...item,
          })),
        };
      });
      // 提取所有 materialId 并去重，额外生成一个 list
      const materialIdList = _(kindList)
        .map("materialId")
        .uniq()
        .map((id) => ({ id }))
        .value();
      return { data, materialIdList };
    },
    // 合并原来的数据，根据相同的typestylespec合并
    mergeSameTypeStyleSpec(kindList) {
      // 根据 type.id, style.id 和 spec.id 分组
      const grouped = _.groupBy(kindList, (item) => {
        return `${item.type.id}-${item.style.id}-${item.spec.id}`;
      });
      // 合并分组
      const mergedData = _.map(grouped, (items) => {
        const { type, style, spec, materialId, img } = items[0]; // 取每组中的第一个元素作为基础，同时保留img字段
        const mergedItem = {
          ..._.cloneDeep(INITAIL_DATA),
          type,
          style,
          spec,
          img, // 保留原有的图片数据
          originalData: items,
        };

        return mergedItem;
      });
      return mergedData;
    },

    //添加类型
    addType() {
      const isTypeEmpty = this.treeList.some((item) => item.name === "");
      if (isTypeEmpty) {
        this.$message.error("请先完善当前类型");
        return;
      }
      this.treeList.push({
        id: "",
        name: "",
        group_name: "",
        children: [{ ..._.cloneDeep(INITAIL_DATA), materialId: "" }],
      });
      // 根据当前的skuMaterialIds新增数组
      let data = [];
      for (const i of this.skuMaterialIds) {
        data.push({ ...INITAIL_DATA, materialId: i.id });
      }
      this.$emit("updateKindList", [...this.kindList, ...data]);
    },
    // 删除类型
    delType(index) {
      const copyData = _.cloneDeep(this.kindList);
      const currentTypeName = this.treeList[index].name;
      this.treeList.splice(index, 1);
      const indices = copyData
        .map((value, index) =>
          value.type.name === currentTypeName ? index : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值

      let newArr = copyData.filter((_, index) => !indices.includes(index));
      this.$emit("updateKindList", newArr);
    },
    // 修改类型
    handleChangeType($event) {
      let currentType = this.oldInputValue;
      let insertData = $event;
      if (this.kindList.some((i) => i.type.name === insertData)) {
        this.$message.error("请勿输入相同类型");
        // 清除oldvalue
        (currentType = ""), (insertData = "");
      }
      const copyData = _.cloneDeep(this.kindList);
      // 找到所有符合的index
      const indices = copyData
        .map((value, index) => (value.type.name === currentType ? index : -1)) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      let newArr = copyData.map((item, index) => {
        if (indices.includes(index)) {
          return {
            ...item,
            type: {
              id: insertData,
              name: insertData,
              group_name: "类型",
            },
          };
        }
        return item; // 其他元素保持不变
      });
      this.$emit("updateKindList", newArr);
    },
    // 修改规格
    handleChangeStyle(item2, $event) {
      const copyData = _.cloneDeep(this.kindList);
      const typeName = item2.type.name;
      let oldStyle = this.oldInputValue;

      let insertData = $event;
      if (
        this.kindList.some(
          (i) => i.style.name === insertData && i.type.name === typeName
        )
      ) {
        this.$message.error("请勿输入相同款型");
        // 清除oldvalue
        (oldStyle = ""), (insertData = "");
      }
      // 找到所有符合的index
      const indices = copyData
        .map((value, index) =>
          value.type.name === typeName && value.style.name === oldStyle
            ? index
            : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      let newArr = copyData.map((item, index) => {
        if (indices.includes(index)) {
          return {
            ...item,
            style: {
              id: insertData,
              name: insertData,
              group_name: "款型",
            },
          };
        }
        return item; // 其他元素保持不变
      });
      this.$emit("updateKindList", newArr);
    },
    // 修改款型
    handleChangeSpec(item2, $event) {
      const copyData = _.cloneDeep(this.kindList);
      const typeName = item2.type.name;
      const styleName = item2.style.name;
      const oldSpec = this.oldInputValue;
      // 找到所有符合的index
      const indices = copyData
        .map((value, index) =>
          value.type.name === typeName &&
          value.style.name === styleName &&
          value.spec.name === oldSpec
            ? index
            : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      let newArr = copyData.map((item, index) => {
        if (indices.includes(index)) {
          return {
            ...item,
            spec: {
              id: $event,
              name: $event,
              group_name: "规格",
            },
          };
        }
        return item; // 其他元素保持不变
      });
      this.$emit("updateKindList", newArr);
    },
    // 选择线图
    onSelectImage(item2) {
      const copyData = _.cloneDeep(this.kindList);

      const typeName = item2.type.name;
      const styleName = item2.style.name;
      const specName = item2.spec.name;

      const indices = copyData
        .map((value, index) =>
          value.type.name === typeName &&
          value.style.name === styleName &&
          value.spec.name === specName
            ? index
            : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      let newArr = copyData.map((item, index) => {
        if (indices.includes(index)) {
          return {
            ...item,
            img: item2.img, // 这里会自动处理图片选择和删除的情况
          };
        }
        return item;
      });
      this.$emit("updateKindList", newArr);
    },
    //添加款型或规格
    addStyleSpec(index) {
      const isStyleOrSpecEmpty = this.treeList[index].children.some(
        (item) => item.style.name === "" || item.spec.name === ""
      );
      if (isStyleOrSpecEmpty) {
        this.$message.error("请先完善当前款型或规格");
        return;
      }

      this.treeList[index].children.push({
        ..._.cloneDeep(INITAIL_DATA),
        materialId: "",
      });

      // 处理原数组
      const copyData = _.cloneDeep(this.kindList);
      for (const i of this.skuMaterialIds) {
        copyData.push({
          ...INITAIL_DATA,
          type: {
            id: this.treeList[index].name,
            name: this.treeList[index].name,
            group_name: "类型",
          },
          materialId: i.id,
        });
      }
      this.$emit("updateKindList", copyData);
    },
    // 删除款型和规格
    delStyleSpec(index, index2) {
      const copyData = _.cloneDeep(this.kindList);
      const type = this.treeList[index].name;
      const style = this.treeList[index].children[index2].style.name;
      const spec = this.treeList[index].children[index2].spec.name;
      this.treeList[index].children.splice(index2, 1);
      const indices = copyData
        .map((value, index) =>
          value.type.name === type &&
          value.style.name === style &&
          value.spec.name === spec
            ? index
            : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值

      let newArr = copyData.filter((_, index) => !indices.includes(index));
      this.$emit("updateKindList", newArr);
    },
    //添加材质
    addSkuMaterial() {
      const isMaterialEmpty = this.skuMaterialIds.some((i) => i.id === "");
      if (isMaterialEmpty) {
        this.$message.error("请先完善当前颜色");
        return;
      }
      this.skuMaterialIds.push({ id: "" });
      const copyData = _.cloneDeep(this.kindList);
      // 获取实际合并后的一条数据
      const grouped = _.groupBy(copyData, (item) => {
        return `${item.type.id}-${item.style.id}-${item.spec.id}`;
      });
      const newArr = _.map(grouped, (items) => {
        const { type, style, spec } = items[0]; // 取每组中的第一个元素作为基础
        const mergedItem = {
          materialId: "",
          type: type || {},
          style: style || {},
          spec: spec || {},
          attr_info: [
            {
              attr_group_name: "款型",
              attr_name: style?.name || "",
              attr_id: style?.id || "",
            },
            {
              attr_group_name: "类型",
              attr_name: type?.name || "",
              attr_id: type?.id || "",
            },
            {
              attr_group_name: "规格",
              attr_name: spec?.name || "",
              attr_id: spec?.id || "",
            },
          ],
          // 其他字段保持不变（可以根据需求扩展）
          img: "",
          imgTitle: "",
          img_arr: "",
          kucun: "",
          cbj: "",
          product_code: "",
          marque: "",
          capacity: "",
          yj: "",
          materialName: "",
          unit: "",
          bag_type: "",
          sj: "",
          bar_code: "",
          bom_nums: "",
          firstMaterialId: 0,
          send_days: "",
          cid: undefined,
          status: "0",
        };

        return mergedItem;
      });
      this.$emit("updateKindList", [...copyData, ...newArr]);
    },
    delSkuMaterial(smIdx, item) {
      if (this.skuMaterialIds.length === 1) {
        return;
      }
      const copyData = _.cloneDeep(this.kindList);
      const indices = copyData
        .map((value, index) => (value.materialId === item.id ? index : -1)) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      this.skuMaterialIds.splice(smIdx, 1);
      const newArr = copyData.filter((_, index) => !indices.includes(index));
      this.$emit("updateKindList", newArr);
    },
    // 更新材质选项
    handleChangeMaterial(e, index) {
      this.$nextTick(() => {
        const selectElement =
          this.$refs.mtRef[index].$el.querySelector("input");
        selectElement.blur();
      });
      if (this.oldMaterialIds.map((i) => i.id).includes(e)) {
        this.$message.error("请勿选择重复颜色");
        this.skuMaterialIds[index].id = this.curFocusMaterialId;
        return;
      }
      const materialId = e;
      const copyData = _.cloneDeep(this.kindList);
      console.log(this.curFocusMaterialId);
      // 找到所有符合的index
      const indices = copyData
        .map((value, index) =>
          value.materialId === this.curFocusMaterialId ? index : -1
        ) // 将符合条件的索引保留，其他设置为-1
        .filter((index) => index !== -1); // 过滤掉-1的值
      console.log("indices", indices);
      if (!indices.length) return;
      let newArr = copyData.map((item, index) => {
        if (indices.includes(index)) {
          return {
            ...item,
            materialId,
          };
        }
        return item; // 其他元素保持不变
      });
      this.$emit("updateKindList", newArr);
    },
    saveOriginMaterial(e) {
      console.log("clk");
      this.curFocusMaterialId = e;
      this.oldMaterialIds = _.cloneDeep(this.skuMaterialIds);
    },
    saveTypeOriginalValue(e) {
      this.oldInputValue = e.target.value;
    },
    delKindList(scope) {
      if (this.kindList.length === 1) {
        this.$emit("updateKindList", _.cloneDeep([INITAIL_DATA]));
        return;
      }
      let copyData = _.cloneDeep(this.kindList);
      copyData.splice(scope.$index, 1);
      this.$emit("updateKindList", copyData);
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<template>
  <div>
    <h3>款型选择</h3>
    <el-button
      @click="addType"
      v-if="!treeList.length"
      icon="el-icon-plus"
    ></el-button>
    <el-row
      :gutter="20"
      class="type-box"
      v-for="(item, index) in treeList"
      :key="index"
    >
      <!-- 类型 -->
      <el-col :span="20" style="margin-top: 25px">
        <el-input
          v-model="item.name"
          @change="handleChangeType($event)"
          @focus="saveTypeOriginalValue"
          placeholder="请填写款型"
        >
          <el-button
            v-if="treeList.length > 1"
            @click="delType(index)"
            slot="append"
            icon="el-icon-delete"
          ></el-button>
        </el-input>
        <el-button
          v-if="index === treeList.length - 1"
          @click="addType"
          icon="el-icon-plus"
        ></el-button>
      </el-col>
      <!-- 款型 -->
      <el-col
        :span="12"
        v-for="(item2, index2) in item.children"
        :key="index2"
        style="margin-top: 15px; display: flex; align-items: center"
      >
        <l-upload
          :limit="1"
          v-model="item2.img"
          text=""
          @onSelectImage="onSelectImage(item2)"
        >
        </l-upload>
        <el-input
          v-model="item2.style.name"
          style="width: 150px; margin-left: 10px"
          @change="handleChangeStyle(item2, $event)"
          @focus="saveTypeOriginalValue"
          placeholder="请填写名称"
        />
        <el-input
          v-model="item2.spec.name"
          style="width: 250px"
          @change="handleChangeSpec(item2, $event)"
          @focus="saveTypeOriginalValue"
          placeholder="请填写规格（mm）"
        >
          <el-button
            v-if="
              item.children.length > 1 && index2 === item.children.length - 1
            "
            @click="delStyleSpec(index, index2)"
            slot="append"
            icon="el-icon-delete"
          ></el-button>
          <el-button
            v-if="index2 === item.children.length - 1"
            @click="addStyleSpec(index)"
            slot="append"
            icon="el-icon-plus"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="8">
        <el-button
          @click="addStyleSpec(index)"
          v-if="!item.children.length"
          icon="el-icon-plus"
          >添加款型和规格</el-button
        >
      </el-col>
    </el-row>
    <h3 style="margin-bottom: 20px">颜色选择</h3>
    <el-row :gutter="20">
      <el-col
        v-for="(smItem, smIdx) in skuMaterialIds"
        :key="`skuId-${smIdx}`"
        :span="8"
        style="margin-bottom: 10px"
      >
        <el-select
          ref="mtRef"
          v-model="smItem.id"
          placeholder="请选择材质/颜色"
          @change="handleChangeMaterial(smItem.id, smIdx)"
          @focus="saveOriginMaterial(smItem.id)"
        >
          <el-option
            v-for="item in skuMaterialList"
            :key="`mat-${smItem.id}-${item.materialName}`"
            :label="item.materialName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-button
          v-if="
            skuMaterialIds.length > 1 && smIdx === skuMaterialIds.length - 1
          "
          @click="delSkuMaterial(smIdx, smItem)"
          icon="el-icon-delete"
        ></el-button>
        <el-button
          v-if="smIdx === skuMaterialIds.length - 1"
          @click="addSkuMaterial"
          icon="el-icon-plus"
        ></el-button>
      </el-col>
    </el-row>
    <el-table :data="kindList" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="img" label="线图" width="200">
        <template #default="{ row }">
          <l-upload :limit="1" v-model="row.img" text=""> </l-upload>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="200" prop="type.name">
      </el-table-column>
      <el-table-column label="款型" width="200" prop="style.name">
      </el-table-column>
      <el-table-column label="规格(mm)" width="200" prop="spec.name">
      </el-table-column>
      <el-table-column prop="materialId" label="颜色材质" width="200">
        <template #default="{ row }">
          {{ skuMaterialListMap[row.materialId] }}
        </template>
      </el-table-column>
      <el-table-column prop="marque" label="型号" width="150">
        <template #default="{ row }">
          <el-input v-model="row.marque" style="width: 120px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="cbj" label="采购价(元)" width="120">
        <template #default="{ row }">
          <el-input v-model="row.cbj" style="width: 80px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="yj" label="供货价(元)" width="120">
        <template #default="{ row }">
          <el-input v-model="row.yj" style="width: 80px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="sj" label="建议零售价(元)" width="120">
        <template #default="{ row }">
          <el-input v-model="row.sj" style="width: 80px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="bom_nums" label="包件数(件)" width="120">
        <template #default="{ row }">
          <el-input v-model="row.bom_nums" style="width: 80px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="capacity" label="体积(m³)" width="120">
        <template #default="{ row }">
          <el-input v-model="row.capacity" style="width: 80px"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="send_days" label="发货天数(天)" width="120">
        <template #default="{ row }">
          <el-select
            v-model="row.send_days"
            placeholder="请选择"
            style="width: 80px !important"
          >
            <el-option
              v-for="item in send_days_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="bag_type" label="整装/组装" width="100">
        <template #default="{ row }">
          <el-select
            v-model="row.bag_type"
            placeholder="请选择"
            style="width: 80px !important"
          >
            <el-option
              v-for="item in bag_type_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否上架" fixed="right">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="delKindList(scope)" type="text" size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style lang="css" scoped>
.type-box {
  margin-bottom: 20px;
}
.type-spec {
  display: flex;
  /* margin-top: 10px; */
}
.img {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 8px;
}

::v-deep .el-input__inner {
  height: 2.5rem !important;
}

.plus-btn {
  margin-top: 10px;
}
</style>
